<template>
  <div class="fz15">
    <van-form @submit="handleSubmit">
      <van-field
        name="typeId"
        label="课程分类"
        required
        :rules="[{ required: true, message: '请选择课程分类' }]"
      >
        <template #input>
          <van-radio-group v-model="formData.typeId">
            <van-radio
              :name="Number(item.id)"
              v-for="item in radioList"
              :key="item.id"
            >
              <template #icon="props">
                <img
                  class="img-icon"
                  :src="props.checked ? activeIcon : inactiveIcon"
                />
              </template>
              {{ item.name }}
            </van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        name="name"
        v-model="formData.name"
        label="课程名称"
        placeholder="请输入课程名称"
        required
        :rules="[{ required: true }]"
      >
      </van-field>
      <van-popup v-model="showPicker" round position="bottom">
        <van-picker
          show-toolbar
          :columns="columns"
          @cancel="showPicker = false"
          @confirm="onConfirm"
        />
      </van-popup>
      <van-field
        required
        label="课程分类"
        name="categoryId"
        v-model="formData.categoryId"
        placeholder="请选择课程分类"
        disabled
        :rules="[{ required: true }]"
        @click="handleClick"
        is-link
      >
      </van-field>
      <van-field
        v-if="isOnline"
        label="直播地址"
        name="link"
        v-model="formData.link"
        placeholder="请输入直播地址"
      />

      <van-field
        v-if="isOnline"
        label="直播密码"
        name="password"
        v-model="formData.password"
        placeholder="请输入直播密码"
      />

      <van-field name="videoType" label="视频类型">
        <template #input>
          <van-radio-group direction="horizontal" v-model="formData.videoType">
            <van-radio :name="0">
              <template #icon="props">
                <img
                  class="img-icon"
                  :src="props.checked ? activeIcon : inactiveIcon"
                />
              </template>
              视频链接
            </van-radio>
            <van-radio :name="1">
              <template #icon="props">
                <img
                  class="img-icon"
                  :src="props.checked ? activeIcon : inactiveIcon"
                />
              </template>
              上传视频
            </van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field name="paid" label="收费类型">
        <template #input>
          <van-radio-group direction="horizontal" v-model="formData.paid">
            <van-radio :name="0">
              <template #icon="props">
                <img
                  class="img-icon"
                  :src="props.checked ? activeIcon : inactiveIcon"
                />
              </template>
              免费
            </van-radio>
            <van-radio :name="1">
              <template #icon="props">
                <img
                  class="img-icon"
                  :src="props.checked ? activeIcon : inactiveIcon"
                />
              </template>
              付费
            </van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        v-if="formData.videoType === 0"
        required
        name="link"
        v-model="formData.link"
        label="视频链接"
        placeholder="请输入视频链接"
        :rules="[{ required: true }]"
      ></van-field>

      <van-field
        v-if="formData.paid === 1"
        label="收费金额"
        name="fee"
        v-model="formData.fee"
        placeholder="请输入收费金额"
        type="number"
      >
      </van-field>

      <van-field name="video" label="视频" v-if="formData.videoType === 1">
        <template #input>
          <van-uploader
            max-count="1"
            accept="video/*"
            :max-size="10 * 1024 * 1024"
            @delete="removeVideo"
            v-model="videoList"
            :after-read="handleAfterRead"
            :upload-icon="require('@/assets/icon/upload-icon.png')"
          />
        </template>
      </van-field>

      <van-field class="imgs" name="imgs" label="课程封面">
        <template #input>
          <van-uploader
            max-count="1"
            :max-size="10 * 1024 * 1024"
            @delete="removeImg"
            v-model="formData.imgs"
            :upload-icon="require('@/assets/icon/upload-icon.png')"
          />
        </template>
      </van-field>
      <van-field
        label="课程简介"
        required
        name="description"
        v-model="formData.description"
        placeholder="请输入课程简介"
        :rules="[{ required: true }]"
        type="textarea"
        rows="6"
      >
      </van-field>

      <div class="button-bottom pd1">
        <van-button block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import {
  Form,
  Field,
  RadioGroup,
  Radio,
  Uploader,
  Button,
  Popup,
  Picker,
} from "vant";
import API from "@/services";
import axios from "axios";
export default {
  data() {
    return {
      showPicker: false,
      columns: [],
      radioList: [],
      formData: {
        typeId: 0,
        videoType: 0,
      },
      activeIcon: require("@/assets/icon/radio-checked.png"),
      inactiveIcon: require("@/assets/icon/radio.png"),
      isOnline: false,
      orginCategoryList: [],
      videoList: [],
      videoArray: [],
    };
  },
  async created() {
    const data = await API.getCourseType();
    const categoryList = await API.getCourseCategory();
    this.radioList = data;
    this.formData.typeId = Number(data[0].id);
    this.columns = categoryList.map((item) => item.name);
    this.orginCategoryList = categoryList;
    if (this.$route.params.type === "edit") {
      const res = await API.getcourseDetailAjax({
        params: { courseId: this.$route.params.id },
      });
      this.formData = {
        ...this.formData,
        ...res,
        typeId: Number(res.typeId),
        imgs: [],
        categoryId: this.orginCategoryList.find(
          (item) => Number(item.id) === res.categoryId
        ).name,
      };
      console.log(res.imgs);
      if (res.imgs) this.formData.imgs = [{ url: res.imgs }];
      console.log(this.formData);
    }
  },
  watch: {
    "formData.typeId": {
      handler() {
        const currentType = this.radioList.find(
          (item) => Number(item.id) === this.formData.typeId
        );
        this.isOnline = currentType && currentType.name.indexOf("直播") > -1;
      },
      immediate: true,
    },
  },
  components: {
    VanForm: Form,
    VanField: Field,
    VanRadioGroup: RadioGroup,
    VanRadio: Radio,
    VanUploader: Uploader,
    VanButton: Button,
    VanPopup: Popup,
    VanPicker: Picker,
  },
  methods: {
    async handleAfterRead(file) {
      const formData = new FormData();
      formData.append("type", 2);
      formData.append("file", file.file);
      const data = await API.uploadimg({ data: formData });
      if (data) {
        this.formData.link = data.url;
      }
    },
    async handleSubmit(val) {
      const maxPrice = this.radioList.find(
        (item) => Number(item.id) === val.typeId
      ).maxPrice;
      if (val.fee && Number(val.fee) > maxPrice) {
        this.$toast.fail("课程价格超过定价上限");
        return;
      }

      if (this.formData.videoType == 1) {
        if (!this.formData.link) {
          this.$toast.fail("请上传视频!");
          return;
        }
      }

      try {
        const categoryId = Number(
          this.orginCategoryList.find((item) => item.name === val.categoryId).id
        );
        const params = {
          ...val,
          categoryId,
        };
        let currentRequest = API.PublishCourse;
        if (this.$route.params.type === "edit") {
          params.id = this.$route.params.id;
          currentRequest = API.updateCourse;
        }
        const uploadRequestList = (this.formData.imgs || []).map((item) => {
          if (!item.file && item.url) {
            return Promise.resolve({ url: item.url });
          }
          const Form = new FormData();
          Form.append("file", item.file);
          Form.append("type", 1);
          return API.uploadimg({ data: Form });
        });
        const resList = await Promise.all(uploadRequestList);
        console.log(resList);
        const imgs = resList.map((item) => item.url).join(",");
        params.imgs =
          imgs ||
          "http://image.16988.com/image/20210602/be84cdd6839b48e4a59f7e04b5cf0334.png";
        //新增上传视频
        params.link = this.videoType == 0 ? params.link : this.formData.link;
        await currentRequest({ data: params });
        this.$toast({
          type: "success",
          message: "发布成功",
        });
        this.$router.go(-1);
      } catch (error) {
        console.log(error.message);
        this.$toast({
          type: "fail",
          message: error.message,
        });
      }
    },
    onConfirm(value) {
      this.formData.categoryId = value;
      this.showPicker = false;
    },
    handleClick() {
      this.showPicker = true;
    },
    removeImg(data) {
      this.formData.imgs = [];
    },
    removeVideo(data) {
      this.videoList = [];
    },
  },
};
</script>
<style lang="scss" scoped>
.imgs {
  margin-bottom: 70px;
}
.img-icon {
  height: 18px;
  width: 18px;
}

>>> .van-uploader__input {
  top: 50%;
  left: 50%;
}
</style>
